import {
  Injectable,
  Inject,
  Provider,
  EventEmitter,
  Optional,
  SkipSelf,
} from '@angular/core';

import { fui_I18N_LANGE } from './i18n-token';

import translationZhCn from './assets/zh_CN';
import translationEnUs from './assets/en_US';

const BCP47Mapping: {[key: string]: string} = {
  en_US: 'en-US',
  zh_CN: 'zh-CN',
};


@Injectable()
export class fuiTranslateService {
  private _lang: string;
  store: any;
  onLangChange = new EventEmitter();

  constructor(@Optional() @Inject(fui_I18N_LANGE) lang: string) {
    this.store = {
      en_US: translationEnUs,
      zh_CN: translationZhCn,
    };
    this._lang = lang || 'zh_CN';
  }

  get langBCP47() {
    return BCP47Mapping[this._lang];
  }

  get lang() {
    return this._lang;
  }

  setLocale(lang: string) {
    this._lang = lang;
    this.onLangChange.emit(this);
  }

  /**
   * 翻译字段
   *
   * @param _key
   */
  translateKey(_key: string) {
    if (!_key) {
      return '';
    }
    const key = _key.toString();
    if (!this.lang || !this.store[this.lang]) {
      return key;
    }
    const store = this.store[this.lang];
    const keyArr = key.split('.');
    let value = store;
    try {
      keyArr.forEach((k) => {
        value = value[k];
      });
      if (typeof value === 'string') {
        return value;
      } else {
        return key;
      }
    } catch (err) {
      return key;
    }
  }
}

// To prevent creating duplicate instance when using lazy-load sub-module (i.e. loadChildren)
export const fui_LOCALE_SERVICE_PROVIDER_FACTORY = (exist: fuiTranslateService, lang: string): fuiTranslateService =>
  exist || new fuiTranslateService(lang);

export const fui_I18N_SERVICE_PROVIDER: Provider = {
  provide   : fuiTranslateService,
  useFactory: fui_LOCALE_SERVICE_PROVIDER_FACTORY,
  deps      : [ [ new Optional(), new SkipSelf(), fuiTranslateService ], fui_I18N_LANGE ],
};
